#pragma once
#include "../server.hpp"
#include <fstream>
#include <string>
#include <vector>
#include <regex>
#include <sys/stat.h>

//  根据状态码获取描述信息
std::unordered_map<int, std::string> _statu_msg = {
    {100,  "Continue"},
    {101,  "Switching Protocol"},
    {102,  "Processing"},
    {103,  "Early Hints"},
    {200,  "OK"},
    {201,  "Created"},
    {202,  "Accepted"},
    {203,  "Non-Authoritative Information"},
    {204,  "No Content"},
    {205,  "Reset Content"},
    {206,  "Partial Content"},
    {207,  "Multi-Status"},
    {208,  "Already Reported"},
    {226,  "IM Used"},
    {300,  "Multiple Choice"},
    {301,  "Moved Permanently"},
    {302,  "Found"},
    {303,  "See Other"},
    {304,  "Not Modified"},
    {305,  "Use Proxy"},
    {306,  "unused"},
    {307,  "Temporary Redirect"},
    {308,  "Permanent Redirect"},
    {400,  "Bad Request"},
    {401,  "Unauthorized"},
    {402,  "Payment Required"},
    {403,  "Forbidden"},
    {404,  "Not Found"},
    {405,  "Method Not Allowed"},
    {406,  "Not Acceptable"},
    {407,  "Proxy Authentication Required"},
    {408,  "Request Timeout"},
    {409,  "Conflict"},
    {410,  "Gone"},
    {411,  "Length Required"},
    {412,  "Precondition Failed"},
    {413,  "Payload Too Large"},
    {414,  "URI Too Long"},
    {415,  "Unsupported Media Type"},
    {416,  "Range Not Satisfiable"},
    {417,  "Expectation Failed"},
    {418,  "I'm a teapot"},
    {421,  "Misdirected Request"},
    {422,  "Unprocessable Entity"},
    {423,  "Locked"},
    {424,  "Failed Dependency"},
    {425,  "Too Early"},
    {426,  "Upgrade Required"},
    {428,  "Precondition Required"},
    {429,  "Too Many Requests"},
    {431,  "Request Header Fields Too Large"},
    {451,  "Unavailable For Legal Reasons"},
    {501,  "Not Implemented"},
    {502,  "Bad Gateway"},
    {503,  "Service Unavailable"},
    {504,  "Gateway Timeout"},
    {505,  "HTTP Version Not Supported"},
    {506,  "Variant Also Negotiates"},
    {507,  "Insufficient Storage"},
    {508,  "Loop Detected"},
    {510,  "Not Extended"},
    {511,  "Network Authentication Required"}
};

// 根据文件后缀获取文件mime
std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac",        "audio/aac"},
    {".abw",        "application/x-abiword"},
    {".arc",        "application/x-freearc"},
    {".avi",        "video/x-msvideo"},
    {".azw",        "application/vnd.amazon.ebook"},
    {".bin",        "application/octet-stream"},
    {".bmp",        "image/bmp"},
    {".bz",         "application/x-bzip"},
    {".bz2",        "application/x-bzip2"},
    {".csh",        "application/x-csh"},
    {".css",        "text/css"},
    {".csv",        "text/csv"},
    {".doc",        "application/msword"},
    {".docx",       "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot",        "application/vnd.ms-fontobject"},
    {".epub",       "application/epub+zip"},
    {".gif",        "image/gif"},
    {".htm",        "text/html"},
    {".html",       "text/html"},
    {".ico",        "image/vnd.microsoft.icon"},
    {".ics",        "text/calendar"},
    {".jar",        "application/java-archive"},
    {".jpeg",       "image/jpeg"},
    {".jpg",        "image/jpeg"},
    {".js",         "text/javascript"},
    {".json",       "application/json"},
    {".jsonld",     "application/ld+json"},
    {".mid",        "audio/midi"},
    {".midi",       "audio/x-midi"},
    {".mjs",        "text/javascript"},
    {".mp3",        "audio/mpeg"},
    {".mpeg",       "video/mpeg"},
    {".mpkg",       "application/vnd.apple.installer+xml"},
    {".odp",        "application/vnd.oasis.opendocument.presentation"},
    {".ods",        "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt",        "application/vnd.oasis.opendocument.text"},
    {".oga",        "audio/ogg"},
    {".ogv",        "video/ogg"},
    {".ogx",        "application/ogg"},
    {".otf",        "font/otf"},
    {".png",        "image/png"},
    {".pdf",        "application/pdf"},
    {".ppt",        "application/vnd.ms-powerpoint"},
    {".pptx",       "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar",        "application/x-rar-compressed"},
    {".rtf",        "application/rtf"},
    {".sh",         "application/x-sh"},
    {".svg",        "image/svg+xml"},
    {".swf",        "application/x-shockwave-flash"},
    {".tar",        "application/x-tar"},
    {".tif",        "image/tiff"},
    {".tiff",       "image/tiff"},
    {".ttf",        "font/ttf"},
    {".txt",        "text/plain"},
    {".vsd",        "application/vnd.visio"},
    {".wav",        "audio/wav"},
    {".weba",       "audio/webm"},
    {".webm",       "video/webm"},
    {".webp",       "image/webp"},
    {".woff",       "font/woff"},
    {".woff2",      "font/woff2"},
    {".xhtml",      "application/xhtml+xml"},
    {".xls",        "application/vnd.ms-excel"},
    {".xlsx",       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml",        "application/xml"},
    {".xul",        "application/vnd.mozilla.xul+xml"},
    {".zip",        "application/zip"},
    {".3gp",        "video/3gpp"},
    {".3g2",        "video/3gpp2"},
    {".7z",         "application/x-7z-compressed"}
};


/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Util是一个服务于http协议模块的工具类

*/
class Util
{
public:
    /*············································

        字符串切割函数,返回切割后的字符串的个数     

    ············································*/
    static size_t Split(const std::string& src, const std::string& sep, std::vector<std::string>* arry)
    {
        size_t offset = 0;  // 指针偏移量
        while (offset < src.size())
        {
            size_t pos = src.find(sep);
            if (pos == std::string::npos) {
                // 没找到,说明offset及后面的内容是一个整体,不需要分割
                arry->push_back(std::move(src.substr(offset)));
                return arry->size();
            }  
            else if (pos == offset) {  // 说明两个sep之间没有字符
                offset += sep.size();
                continue;
            }
            else {
                // 两个sep之间有字符串,需要切割
                arry->push_back(std::move(src.substr(offset, pos - offset)));
                offset += sep.size();
            }
        }
        return arry->size();
    }
    /*············································

        读取文件的所有内容,将读取的内容放到buf中     

    ············································*/
    static bool ReadFile(const std::string& filename, std::string* buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (ifs.is_open() == false) {
            LOG(Warning, "ReadFile open file: \"%s\" failed!", filename.c_str());
            return false;
        }
        size_t fileSize = 0;
        // 跳转读写位置到末尾
        ifs.seekg(0, ifs.end);
        // 读取当前位置相对于起始位置的偏移量
        fileSize = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        // 开好空间
        buf->resize(fileSize);
        // 将文件内容读取到buf中
        ifs.read(&(*buf)[0], fileSize);
        if (ifs.good() == false) {
            LOG(Warning, "Read file: \"%s\" failed!", filename.c_str());
            ifs.close();
            return false;
        }
        // 读取完成,关闭文件
        ifs.close();
        return true;
    }
    /*············································

                    向文件中写入内容

    ············································*/
    static bool WriteFile(const std::string& filename, const std::string& buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if(ofs.is_open() == false) {
            LOG(Warning, "WriteFile open \file: \"%s\" failed!", filename.c_str());
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good() == false) {
            LOG(Warning, "Write file: \"%s\" failed!", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    /*············································

        URL编码,避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
        编码格式: 将特殊字符的ascii值,转换为两个16进制字符,前缀%   C++ -> C%2B%2B
        不编码的特殊字符: RFC3986文档规定 . - _ ~ 字母,数字属于绝对不编码字符
        RFC3986文档规定，编码格式 %HH 
        W3C标准中规定,查询字符串中的空格,需要编码为+,解码则是+转空格 

    ············································*/
    static std::string UrlEncode(const std::string& url, bool convert_space_to_plus)
    {   
        std::string res;
        for (auto& c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c)) {
                res += c;
                continue;
            }
            else if (c == ' ' && convert_space_to_plus == true) {
                res += '+';
                continue;
            }
            else {
                // 剩下的字符都是需要编码成%HH 格式
                char tmp[4] = {0};
                snprintf(tmp, 4, "%%%02X", c);
                res += tmp;
            }
        }
        return res;
    }
    /*············································

            将十六进制数转换为十进制数字   

    ············································*/
    static char HEXToI(char c)
    {
        if (c >= '0' && c <= '9') {
            return c - '0';
        }else if (c >= 'a' && c <= 'z') {
            return c - 'a' + 10;
        }else if (c >= 'A' && c <= 'Z') {
            return c - 'A' + 10;
        }
        return -1;
    }
    /*············································

                    解码URL    

    ············································*/
    static std::string UrlDecode(const std::string& url, bool convert_plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); ++i) 
        {
            if (url[i] == '+' && convert_plus_to_space == true) {
                // 将 '+' 转化为' '
                res += ' ';
                continue;
            }
            if (url[i] == '%' && (i + 2) < url.size()) {
                // 遇到%,则将紧随其后的2个字符转化为数字,第一个数字向左移动4位(*16),然后+第二个数字
                // %2B --> (2 << 4) + 11,   2<<4: 2*16  11: B(16进制) 
                char v1 = HEXToI(url[i+1]);
                char v2 = HEXToI(url[i+2]);
                char v = v1 + v2;
                res += v;
                i += 2;
                continue;
            }
            // 无需转码
            res += url[i];
        }
        return res;
    }
    /*············································

            根据响应状态码获取其描述信息

    ············································*/
    static std::string StatuDesc(int statu)
    {
        auto it = _statu_msg.find(statu);
        if (it != _statu_msg.end()) {
            return it->second;
        }
        return "Unkonw";
    }
    /*············································

                根据文件后缀获取文件Mime    

    ············································*/
    static std::string ExtMime(const std::string &filename)
    {
        // 先获取文件拓展名
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos) {
            // 普通二进制文件
            return "application/octet-stream";
        }
        // 根据拓展名,获取mime
        std::string ext = std::move(filename.substr(pos));
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end()) {
            return "application/octet-stream";
        }
        return it->second;
    }
    /*············································

              判断一个文件是否为一个目录   

    ············································*/
    static bool IsDirectory(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0) {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }
    /*············································

            判断一个文件是否是一个普通文件  

    ············································*/
    static bool IsRegular(const std::string& filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0) {
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    /*············································

             判断http请求资源是否有效   
          /index.html 前边的/叫做相对根目录
          映射的是某个服务器上的子目录
          客户端只能请求相对根目录中的资源
          其他地方的资源都不予理会

    ············································*/
    static bool ValidPath(const std::string& path)
    {
        // 按照/进行路径分割,根据有多少子目录,计算目录深度,有多少层,深度不能小于0
        std::vector<std::string> subdir;
        Split(path, "/", &subdir);
        int level = 0;
        for (auto& dir : subdir)
        {
            if (dir == "..") {
                --level;
                if (level < 0) {
                    return false;
                }
                continue;
            }
            level++;
        }
        return true;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Http请求信息模块

*/
class HttpRequest
{
public:
    std::string _method;  // 请求方法
    std::string _path;    // 请求资源的路径
    std::string _version; // 请求协议的版本
    std::string _body;    // 请求正文
    std::smatch _matches;  // 资源路径的正则提取数据
    std::unordered_map<std::string, std::string> _headers;  // 头部字段字符串的Hash
    std::unordered_map<std::string, std::string> _params;   // 查询字符串的Hash
public:
    HttpRequest() :_version("HTTP/1.1")
    {}
    /*············································

                    清空请求信息

    ············································*/
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version.clear();
        _body.clear();
        std::smatch matches;
        _matches.swap(matches);
        _headers.clear();
        _params.clear();
    }
    /*············································

                  插入头部字段信息  

    ············································*/
    void SetHashHeader(const std::string& key, const std::string& val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    /*············································

              判断是否存在某个指定头部字段  

    ············································*/
    bool HashHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end()) {
            return false;
        }
        return true;
    }
    /*············································

                获取某个指定头部字段的值    

    ············································*/
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end()) {
            return "";
        }
        return it->second;
    }
    /*············································

                    插入查询字符串 

    ············································*/
    void SetParam(const std::string& key, const std::string& val)
    {
        _params.insert(std::make_pair(key, val));
    }
    /*············································

            判断是否存在某个指定的查询字符串 

    ············································*/
    bool HashParam(const std::string& key) const
    {
        auto it = _params.find(key);
        if (it == _params.end()) {
            return false;
        }
        return true;
    }
    /*············································

              获取某个指定的查询字符串的值    

    ············································*/
    std::string GetParam(const std::string& key) const
    {
        auto it = _params.find(key);
        if (it == _params.end()) {
            return "";
        }
        return it->second;
    }
    /*············································

                    获取请求正文长度  

    ············································*/
    size_t ContentLength() const
    {
        // Content-Length: 1234\r\n
        bool ret = HashHeader("Content-Length");
        if (ret == false) {
            return 0;
        }
        std::string clen = GetHeader("Content-Length");
        return std::stoi(clen);
    }
    /*············································

                    判断是否是短链接

    ············································*/
    bool IsClose() const
    {
        // 没有Connection字段,或者Connection字段的值是close,则是短链接
        if (HashHeader("Connection") && GetHeader("Connection") == "keep-alive") {
            return false;
        }
        return true;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Http响应信息模块

*/
class HttpResponse 
{
public:
    int _statu;     // 状态码
    bool _redirect_flag;  // 是否重定向标志位
    std::string _body;    // 响应正文
    std::string _redirect_url;  // 重定向url
    std::unordered_map<std::string, std::string> _headers;  
public:
    HttpResponse() :_redirect_flag(false), _statu(200)
    {}
    HttpResponse(int statu) :_redirect_flag(false), _statu(statu)
    {}
    /*············································

                    清空响应信息

    ············································*/
    void Reset()
    {
        _statu = 200;
        _redirect_url = false;
        _body.clear();
        _redirect_url.clear();
        _headers.clear();
    }
    /*············································

                插入响应头部字段信息

    ············································*/
    void SetHeader(const std::string& key, const std::string& val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    /*············································

              判断是否存在某个指定头部字段

    ············································*/
    bool HashHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end()) {
            return false;
        }
        return true;
    }
    /*············································

              获取某个指定头部字段的值    

    ············································*/
    std::string GetHeader(const std::string& key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end()) {
            return "";
        }
        return it->second;
    }
    /*············································

                    设置响应正文

    ············································*/
    void SetContent(const std::string& body, const std::string& type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    /*············································

                    设置重定向url 

    ············································*/
    void SetDircert(const std::string& url, int statu = 302)
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    /*············································

                判断是否是短链接

    ············································*/
    bool IsClose() const
    {
        // 没有Connection字段,或者Connection字段的值是close,则是短链接
        if (HashHeader("Connection") && GetHeader("Connection") == "keep-alive") {
            return false;
        }
        return true;
    }
};


/////////////////////////////////////////////////////////////////////////////////////////////
/*

    Http上下文模块

*/
// 用于描述Http接收及解析的阶段状态
typedef enum 
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
}HttpRecvStatu;
class HttpContext
{
    const int _max_line = 8192;
private:
    int _resp_statu;       // 响应状态码
    HttpRequest _request;  // 已经解析得到的请求信息
    HttpRecvStatu _recv_statu;  // 当前接收及解析的阶段状态
private:
    /*············································

                  接收Http请求的请求行   

    ············································*/
    bool RecvHttpLine(Buffer* buf)
    {
        // 判断是否处于接收请求行状态
        if (_recv_statu != RECV_HTTP_LINE) {
            return false;
        }
        // 1. 获取一行数据,带有末尾的换行符
        std::string line = buf->GetLine();
        // 2. 判断获取到的数据情况
        if (line.size() == 0) {
            // 缓冲区的数据不足一行,判断缓冲区的可读长度
            // 如果可读数据长度很长了却还不足一行,则肯定是有问题的
            if (buf->ReadAbleSize() > _max_line) {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;  // URL TOO LONG
                return false;
            }
            // 缓冲区中数据不足一行,但是不多,则等待新的数据到来
            return true;
        }
        if (line.size() > _max_line) {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414; // URI TOO LONG
            return false;
        }
        // 解析请求首行数据
        bool ret = ParseHttpLine(std::move(line));
        if (ret == false) {
            return false;
        }
        // 首行数据处理完毕,进入头部获取阶段
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }
    /*············································

                  解析Http请求的请求行

    ············································*/
    bool ParseHttpLine(const std::string& line)
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|OUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        /*
            (GET|HEAD|POST|PUT|DELETE)    表示匹配并提取其中一个字符串
            [^?]*                [^?]匹配单个非？字符,后边的*表示0个或多个非？字符
            \\?(.*)              \\? 表示原始的字符?  (.*)表示提取?之后的任意字符0次或多次,直到遇到空格
            (HTTP/1\\.[01])      表示匹配并提取以HTTP/1.开始,后边有个0或者1的字符串
            (?:\n|\r\n)?         (?:...)表示匹配某个格式字符串,但是不提取   (...)?表示前面的整个组是可选的,即匹配前面的表达式0次或1次
            std::regex::icase    表示正则表达式匹配时忽略大小写
        */
        bool ret = std::regex_match(line, matches, e);
        if (ret == false) {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            return false;
        }
        /*
        eg:
            0: GET /baidu/s?word=hello&rsv_opt=1 HTTP/1.1
            1: GET
            2: /baidu/s
            3: world=hello&rsv_opt=1
            4: HTTP/1.1
        */
        // 请求方法的获取
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        // 资源路径的获取,需要进行URL解析,但不需要+转空格
        _request._path = Util::UrlDecode(matches[2], false);
        // 协议版本的获取
        _request._version = matches[4];
        // 查询字符串的获取与处理
        std::vector<std::string> query_string_arry;
        std::string query_string = matches[3];
        Util::Split(query_string, "&", &query_string_arry);
        // 针对各个字符串,以 = 符号进行分割,得到key和val,得到后需要进行解码
        for(auto& str : query_string_arry)
        {
            size_t pos = str.find("=");
            if (pos == std::string::npos) {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400; // BAD REQUEST
                return false;
            }
            std::string key = std::move(Util::UrlDecode(std::move(str.substr(0, pos)), true));
            std::string val = std::move(Util::UrlDecode(std::move(str.substr(pos + 1)), true));
            _request.SetParam(std::move(key), std::move(val));
        }
        return true;
    }
    /*············································

                接收Http请求的头部数据   

    ············································*/
    bool RecvHttpHead(Buffer* buf)
    {
        if (_recv_statu != RECV_HTTP_HEAD) {
            return false;
        }
        // 一行一行取出数据,直到遇到空行为止; 头部的格式 key: val\r\n key: val\r\n \r\n 
        while (1)
        {
            std::string line = buf->GetLine();
            // 2. 判断获取到的数据情况
            if (line.size() == 0) {
                // 缓冲区的数据不足一行,判断缓冲区的可读长度
                // 如果可读数据长度很长了却还不足一行,则肯定是有问题的
                if (buf->ReadAbleSize() > _max_line) {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414;  // URL TOO LONG
                    return false;
                }
                // 缓冲区中数据不足一行,但是不多,则等待新的数据到来
                return true;
            }
            if (line.size() > _max_line) {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // URI TOO LONG
                return false;
            }
            // 判断是否到了空行,即头部字段结束的位置
            if (line == "\n" || line == "\r\n") {
                break;
            }
            bool ret = ParseHttpHead(line);
            if (ret == false) {
                return false;
            }
        }
        // 头部处理完毕,进入正文获取阶段
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }
    /*············································

                解析Http请求的头部数据   

    ············································*/
    bool ParseHttpHead(std::string &line)
    {
        // key: val\r\nkey: val\r\n\r\n
        if (line.back() == '\n') {
            // 如果末尾是换行符则去掉换行符
            line.pop_back();
        }
        if (line.back() == '\r') {
            // 如果末尾是回车符则去掉回车符
            line.pop_back();
        }
        size_t pos = line.find(": ");
        if (pos == std::string::npos) {
            _recv_statu= RECV_HTTP_ERROR;
            _resp_statu = 400;  // BAD REQUEST
            return false;
        }
        std::string key = std::move(line.substr(0, pos));
        std::string val = std::move(line.substr(pos + 2));
        _request.SetHashHeader(key, val);
        return true;
    }
    /*············································

                 接收Http请求的正文 

    ············································*/
    bool RecvHttpBody(Buffer* buf)
    {
        if (_recv_statu != RECV_HTTP_BODY) {
            return false;
        }
        // 1.获取正文长度
        size_t content_length = _request.ContentLength();
        if (content_length == 0) {
            // 没有正文,则HTTP请求接收解析完毕
            _recv_statu =  RECV_HTTP_OVER;
            return true;
        }
        // 2. 当前已经接收了多少正文,其实就是往_request._body中放了多少数据
        size_t real_len = content_length - _request._body.size();
        // 3. 接收正文放到body中
        // 缓冲区中的数据,包含了当前请求的全部正文
        if (buf->ReadAbleSize() >= real_len) {
            _request._body.append(buf->ReadPosition(), real_len);
            buf->MoveReadOffset(real_len);
            // 全部数据已接收解析
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 缓冲区中的数据,只是部分正文数据,则全部读取,然后等待新数据到来
        _request._body.append(buf->ReadPosition(), buf->ReadAbleSize());
        buf->MoveReadOffset(buf->ReadAbleSize());
        return true;
    }
public:
    HttpContext() :_resp_statu(200), _recv_statu(RECV_HTTP_LINE)
    {}
    /*············································

                    清空Http的上下文   

    ············································*/
    void Reset()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.Reset();
    }
    /*············································

                    获取响应状态码    

    ············································*/
    int GetRespStatu() const
    {
        return _resp_statu;
    }
    /*············································

            获取当前接受及解析的阶段状态

    ············································*/
    HttpRecvStatu GetRecvStatu() const
    {
        return _recv_statu;
    }
    /*············································

                获取已解析得到的请求信息

    ············································*/
    HttpRequest& GetRequest()
    {
        return _request;
    }
    /*············································

                  接收并解析HTTP请求

    ············································*/
    void RecvHttpRequest(Buffer* buf)
    {
        // 不同的状态做不同的事情
        switch (_recv_statu)
        {
            // 这里不要break,因为处理完请求行后,应该立即处理头部,而不是退出等新数据
            case RECV_HTTP_LINE: RecvHttpLine(buf);
            case RECV_HTTP_HEAD: RecvHttpHead(buf);
            case RECV_HTTP_BODY: RecvHttpBody(buf);
        }
        return;
    }
};

/////////////////////////////////////////////////////////////////////////////////////////////
/*

    HttpServer是对HTTP模块的封装

*/
class HttpServer
{
    using Handler = std::function<void(const HttpRequest&, HttpResponse*)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    using PtrConnection = std::shared_ptr<Connection>;
    static const uint32_t _default_timeout = 10;
private:
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _base_dir;  // 静态资源根目录
    TcpServer _server;
    private:
    /*············································

                错误响应处理方式

    ············································*/
    void ErrorHandler(HttpResponse& rsp)
    {
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp._statu);
        body += " ";
        body += Util::StatuDesc(rsp._statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据,当作相应正文,放入rsp中
        rsp.SetContent(body, "text/html");
    }
    /*············································

    将HttpResponse中的要素按照http协议格式进行组织发送    

    ············································*/
    void WriteResponse(const PtrConnection& conn, const HttpRequest& req, HttpResponse& rsp)
    {
        // 1. 先完善头部字段
        if (req.IsClose() == true) {
            rsp.SetHeader("Connection", "close");
        }
        else {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HashHeader("Content-Length") == false) {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HashHeader("Content-Type") == false) {
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if (rsp._redirect_flag == true) {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        // 2. 将rsp中的要素,按照http协议格式进行组织
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._statu) << " " << Util::StatuDesc(rsp._statu) << "\r\n";
        for (auto& head : rsp._headers)
        {
            rsp_str << head.first << ": " << head.second << "\r\n";
        }
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        // 3. 发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }
    /*············································

                判断是否是静态资源请求

    ············································*/
    bool IsFileHandler(const HttpRequest &req)
    {
        // 1. 必须设置了静态资源目录
        if (_base_dir.empty()) {
            return false;
        }
        // 2. 请求方法必须是GET或者HEAD
        if (req._method != "GET" && req._method != "HEAD") {
            return false;
        }
        // 3. 请求的资源路径必须是一个合法路径
        if (Util::ValidPath(req._path) == false) {
            return false;
        }
        // 4. 请求的资源必须存在,且是一个合法路径
        std::string req_path = _base_dir += req._path;
        if (req._path.back() == '/') {
            req_path += "index.html";
        }
        if (Util::IsRegular(req_path) == false) {
            return false;
        }
        return true;
    }
    /*············································

    静态资源的请求处理,将静态资源文件的数据读取出来
    放到rsp的body中,并设置mime 

    ············································*/
    void FileHandler(const HttpRequest& req, HttpResponse* rsp)
    {
        std::string req_path = _base_dir += req._path;
        if (req._path.back() == '/') {
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, &rsp->_body);
        if (ret == false) {
            return;
        }
        std::string mime = Util::ExtMime(req_path);
        rsp->SetHeader("Content-Type", mime);
        return;
    }
    /*············································

                功能性请求的处理函数     

    ············································*/
    void Dispather(HttpRequest& req, HttpResponse* rsp, Handlers &handlers)
    {
        // 在对应请求方法的路由表中,查找是否含有对应资源请求的处理函数,有则调用,没有则发送404
        // 路由表存值键对 --- 正则表达式 & 处理函数
        // 使用正则表达式,对请求的资源路径进行正则匹配,匹配成功就使用相应函数进行处理
        // /numbers/(\d+) 
        for (auto& handler : handlers)
        {
            const std::regex &re = handler.first;
            const Handler& functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if (ret == false) {
                continue;
            }
            return functor(req, rsp);  // 传入请求信息,和空的rsp,执行处理函数
        } 
        rsp->_statu = 404;
    }
    /*············································

            请求路由,分辨请求是静态资源
            请求还是功能性请求,并处理

    ············································*/
    void Route(HttpRequest &req, HttpResponse *rsp)
    {
        // 1. 对请求进行分辨,是一个静态资源请求,还是一个功能性请求
        //      静态资源请求,则进行静态资源的获取
        //      功能性请求,则需要通过几个请求路由表来确定是否有处理函数
        //      既不是静态资源请求,也没有设置对应的功能性请求处理函数,就返回403
        if (IsFileHandler(req) == true) {
            // 是一个静态资源的请求,则进行静态资源请求的处理
            return FileHandler(req, rsp);
        }
        // 非静态资源请求
        if (req._method == "GET" || req._method == "HEAD") {
            return Dispather(req, rsp, _get_route);
        }
        else if (req._method == "POST") {
            return Dispather(req, rsp, _post_route);
        }
        else if (req._method == "PUT") {
            return Dispather(req, rsp, _put_route);
        }
        else if (req._method == "DELETE") {
            return Dispather(req, rsp, _delete_route);
        }
        else{
            rsp->_statu = 405;  //  Method Not Allowed
            return;
        }
    }
    /*············································

            连接阶段处理函数,设置上下文   

    ············································*/
    void OnConnected(const PtrConnection& conn)
    {
        conn->SetContext(HttpContext());
        LOG(Info, "new con, con_id: %d", conn->GetId());
    }
    /*············································

                缓冲区数据解析+处理     

    ············································*/
    void OnMessage(const PtrConnection& conn, Buffer* buffer)
    {
        while(buffer->ReadAbleSize() > 0)
        {
            // 1. 获取上下文
            HttpContext* context = conn->GetContext()->get<HttpContext>();
            // 2. 通过上下文对缓冲区数据进行解析,得到HttpRequest对象
            //   1. 如果缓冲区的数据解析出错,就直接回复出错响应
            //   2. 如果解析正常,且请求已经获取完毕,才开始区进行处理
            context->RecvHttpRequest(buffer);
            HttpRequest& req = context->GetRequest();
            HttpResponse resp(context->GetRespStatu());
            if (context->GetRespStatu() >= 400) {
                // 进行错误响应,关闭连接
                ErrorHandler(resp);   // 填充一个错误显示页面数据到rsp中
                WriteResponse(conn, req, resp);      // 组织响应发送给客户端
                context->Reset();
                buffer->MoveReadOffset(buffer->ReadAbleSize());  // 出错了就把缓冲区数据清空
                conn->ShutDown();  // 关闭连接
                return;
            }
            if (context->GetRecvStatu() != RECV_HTTP_OVER) {
                // 当前请求还没有接收完整则退出,等待新数据到来再重新继续处理
                return;
            }
            // 3. 请求路由+业务处理
            Route(req, &resp);
            // 4. 对比HttpResponse进行组织发送
            WriteResponse(conn, req, resp);
            // 5. 重置上下文
            context->Reset();
            // 6. 根据长短连接判断是否关闭连接或者继续处理
            if (resp.IsClose() == true) {
                conn->ShutDown();  // 短链接则直接关闭
            }
        }
        return;
    }
public:
    HttpServer(const uint16_t port, uint32_t timeout = _default_timeout) :_server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    /*············································

                设置静态资源根目录

    ············································*/
    void SetBaseDir(const std::string &path)
    {
        assert(Util::IsDirectory(path) == true);
        _base_dir = path;
    }
    /*············································

    设置/添加,请求(请求的正则表达式)与处理函数的Hash        

    ············································*/
    void Get(const std::string& pattern, const Handler& handler)
    {
        _get_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string& pattern, const Handler& handler)
    {
        _post_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string& pattern, const Handler& handler)
    {
        _put_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string& pattern, const Handler& handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    /*············································

               设置子Reactor线程数量 

    ············································*/
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    /*············································

                服务器开始监听

    ············································*/
    void Listen()
    {
        _server.Start();
    }
};